package pri.damai.xiaowu.usercenter.sysauth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.enums.ResultCommonEnum;
import pri.damai.xiaowu.common.core.exception.GlobalException;
import pri.damai.xiaowu.usercenter.sysauth.entity.SysRole;
import pri.damai.xiaowu.usercenter.sysauth.entity.SysUserRole;
import pri.damai.xiaowu.usercenter.sysauth.repository.SysRoleDao;
import pri.damai.xiaowu.usercenter.sysauth.service.SysRoleService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色表(SysRole)表服务实现类
 * @Desc
 * @Author DaMai
 * @Date 2022-03-03 17:00:32
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    @Resource
    SysUserRoleServiceImpl userRoleService;
    @Resource
    SysRoleDao roleDao;

    @Override
    public List<SysRole> getRoleByUserId(Long userId) {

        LambdaQueryWrapper<SysUserRole> wrapper = userRoleService.getLambda()
                .eq(SysUserRole::getUserId, userId);
        List<Integer> roleIds = userRoleService.list(wrapper)
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(roleIds)) {
            return new ArrayList<>();
        }

        return this.listByIds(roleIds);
    }

    @Override
    public Set<SysRole> getRoleByUserIdAndSysId(Integer userId, Integer sysId) {

        if (Objects.isNull(userId) || Objects.isNull(sysId)) {
            GlobalException.throwException(ResultCommonEnum.SERVER_DATA_ERROR.code(), "用户Id、系统Id 不可为空。");
        }

        return roleDao.getRoleByUserIdAndSysId(userId, sysId);
    }

    public LambdaQueryWrapper<SysRole> getLambda() {
        return new LambdaQueryWrapper<>();
    }
}
